<template>
  <div class="folder-details">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="backFn" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>

        <div class="folder-info">
          <div class="folder-icon">
            <el-icon><FolderOpened /></el-icon>
          </div>
          <div class="folder-text">
            <h2>{{ folderName || '文件夹详情' }}</h2>
            <p>{{ tableData.length }} 个文件</p>
          </div>
        </div>
      </div>

      <div class="header-actions">
        <el-button @click="refreshFiles">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button type="primary" @click="$router.push('/fileupload')">
          <el-icon><Upload /></el-icon>
          上传文件
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon files">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ tableData.length }}</div>
                <div class="stats-label">文件总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon size">
                <el-icon><Coin /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ totalSize }}</div>
                <div class="stats-label">总大小</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon images">
                <el-icon><Picture /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ imageCount }}</div>
                <div class="stats-label">图片文件</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon videos">
                <el-icon><VideoPlay /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ videoCount }}</div>
                <div class="stats-label">视频文件</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索文件名..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-select v-model="fileTypeFilter" placeholder="文件类型" clearable>
            <el-option label="全部类型" value="" />
            <el-option label="图片" value="image" />
            <el-option label="视频" value="video" />
            <el-option label="音频" value="audio" />
            <el-option label="文档" value="document" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <div class="view-controls">
            <el-radio-group v-model="viewMode">
              <el-radio-button label="table">
                <el-icon><List /></el-icon>
                列表
              </el-radio-button>
              <el-radio-button label="grid">
                <el-icon><Grid /></el-icon>
                网格
              </el-radio-button>
            </el-radio-group>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 文件内容 -->
    <div class="files-content">
      <!-- 表格视图 -->
      <div v-if="viewMode === 'table'">
        <el-table
          :data="filteredFiles"
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />

          <el-table-column label="文件名" min-width="300">
            <template #default="{ row }">
              <div class="file-cell">
                <div class="file-icon">{{ getFileIcon(row.filename) }}</div>
                <span class="file-name">{{ row.filename }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="size" label="文件大小" width="120" />
          <el-table-column prop="created_at" label="创建时间" width="180" />

          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="previewFile(row)">
                <el-icon><View /></el-icon>
                预览
              </el-button>
              <el-button size="small" @click="downloadFile(row)">
                <el-icon><Download /></el-icon>
                下载
              </el-button>
              <el-button type="danger" size="small" @click="deleteFile(row.id)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 网格视图 -->
      <div v-else class="grid-view">
        <div v-if="filteredFiles.length === 0" class="empty-state">
          <el-empty description="文件夹为空">
            <el-button type="primary" @click="$router.push('/fileupload')">
              上传第一个文件
            </el-button>
          </el-empty>
        </div>

        <div v-else class="file-grid">
          <div
            v-for="file in filteredFiles"
            :key="file.id"
            class="file-card"
            @click="previewFile(file)"
          >
            <div class="file-preview">
              <div class="file-icon-large">{{ getFileIcon(file.filename) }}</div>
            </div>

            <div class="file-info">
              <div class="file-name" :title="file.filename">
                {{ file.filename }}
              </div>
              <div class="file-meta">
                <span class="file-size">{{ file.size }}</span>
                <span class="file-date">{{ file.created_at }}</span>
              </div>
            </div>

            <div class="file-actions" @click.stop>
              <el-dropdown trigger="click">
                <el-button type="text" class="action-btn">
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="previewFile(file)">
                      <el-icon><View /></el-icon>
                      预览
                    </el-dropdown-item>
                    <el-dropdown-item @click="downloadFile(file)">
                      <el-icon><Download /></el-icon>
                      下载
                    </el-dropdown-item>
                    <el-dropdown-item @click="deleteFile(file.id)" divided>
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>

      <!-- 批量操作 -->
      <div v-if="selectedFiles.length > 0" class="batch-actions">
        <div class="batch-info">
          已选择 {{ selectedFiles.length }} 个文件
        </div>
        <div class="batch-buttons">
          <el-button @click="batchDownload">
            <el-icon><Download /></el-icon>
            批量下载
          </el-button>
          <el-button type="danger" @click="batchDelete">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import {
  ArrowLeft,
  FolderOpened,
  Refresh,
  Upload,
  Document,
  Coin,
  Picture,
  VideoPlay,
  Search,
  List,
  Grid,
  View,
  Download,
  Delete,
  MoreFilled
} from "@element-plus/icons-vue";
import { getFilesApi, deleteApi, downloadApi } from "@/utils/api.js";

const route = useRoute();
const router = useRouter();

// 响应式数据
const tableData = ref([]);
const loading = ref(false);
const searchKeyword = ref("");
const fileTypeFilter = ref("");
const viewMode = ref("table");
const selectedFiles = ref([]);
const folderName = ref("");

// 获取当前跳转进来的文件夹id
const folderId = route.params.id;

// 计算属性
const filteredFiles = computed(() => {
  let files = tableData.value;

  // 按关键词搜索
  if (searchKeyword.value) {
    files = files.filter(file =>
      file.filename.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }

  // 按文件类型筛选
  if (fileTypeFilter.value) {
    files = files.filter(file => {
      const filename = file.filename.toLowerCase();
      switch (fileTypeFilter.value) {
        case 'image':
          return /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(filename);
        case 'video':
          return /\.(mp4|avi|mov|wmv|flv|mkv)$/i.test(filename);
        case 'audio':
          return /\.(mp3|wav|flac|aac|ogg)$/i.test(filename);
        case 'document':
          return /\.(pdf|doc|docx|xls|xlsx|ppt|pptx|txt)$/i.test(filename);
        case 'other':
          return !/\.(jpg|jpeg|png|gif|bmp|webp|mp4|avi|mov|wmv|flv|mkv|mp3|wav|flac|aac|ogg|pdf|doc|docx|xls|xlsx|ppt|pptx|txt)$/i.test(filename);
        default:
          return true;
      }
    });
  }

  return files;
});

const totalSize = computed(() => {
  const total = tableData.value.reduce((sum, file) => {
    return sum + parseFloat(file.size.replace('MB', ''));
  }, 0);
  return total > 1024 ? `${(total / 1024).toFixed(1)} GB` : `${total.toFixed(1)} MB`;
});

const imageCount = computed(() => {
  return tableData.value.filter(file =>
    /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(file.filename)
  ).length;
});

const videoCount = computed(() => {
  return tableData.value.filter(file =>
    /\.(mp4|avi|mov|wmv|flv|mkv)$/i.test(file.filename)
  ).length;
});

// 方法
const loadFiles = async () => {
  loading.value = true;
  try {
    const response = await getFilesApi({ id: folderId });
    if (response.code === 200) {
      tableData.value = response.data.data.map((item) => ({
        ...item,
        created_at: item.created_at.split("T")[0],
        size: item.size + "MB"
      }));

      // 可以从API获取文件夹名称，这里暂时使用默认值
      folderName.value = `文件夹 ${folderId}`;
    }
  } catch (error) {
    console.error("加载文件失败:", error);
    ElMessage.error("加载文件失败");
  } finally {
    loading.value = false;
  }
};

const refreshFiles = () => {
  loadFiles();
  ElMessage.success("已刷新文件列表");
};

const backFn = () => {
  router.back();
};

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
};

const handleSelectionChange = (selection) => {
  selectedFiles.value = selection;
};

// 预览文件
const previewFile = (file) => {
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000';
  const username = localStorage.getItem('username');
  const previewUrl = `${baseUrl}/${username}/${file.relativeFilePath}`;
  window.open(previewUrl, '_blank');
};

// 下载文件
const downloadFile = async (file) => {
  try {
    const response = await downloadApi({ id: file.id });
    if (response) {
      const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000';
      const username = localStorage.getItem('username');
      const downloadUrl = `${baseUrl}/${username}/${file.relativeFilePath}`;

      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = file.filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      ElMessage.success('开始下载');
    }
  } catch (error) {
    console.error('下载失败:', error);
    ElMessage.error('下载失败，请重试');
  }
};

// 删除文件
const deleteFile = async (id) => {
  try {
    await ElMessageBox.confirm(
      "确定要删除这个文件吗？此操作不可恢复。",
      "确认删除",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await deleteApi({ id });
    if (response.code === 200) {
      ElMessage.success("删除成功");
      await loadFiles();
    } else {
      ElMessage.error("删除失败");
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("删除失败:", error);
      ElMessage.error("删除失败，请重试");
    }
  }
};

// 批量下载
const batchDownload = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning("请先选择要下载的文件");
    return;
  }

  try {
    for (const file of selectedFiles.value) {
      await downloadFile(file);
      // 添加延迟避免同时下载太多文件
      await new Promise(resolve => setTimeout(resolve, 500));
    }
    ElMessage.success(`开始下载 ${selectedFiles.value.length} 个文件`);
  } catch (error) {
    console.error("批量下载失败:", error);
    ElMessage.error("批量下载失败");
  }
};

// 批量删除
const batchDelete = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning("请先选择要删除的文件");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedFiles.value.length} 个文件吗？此操作不可恢复。`,
      "确认批量删除",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const promises = selectedFiles.value.map(file => deleteApi({ id: file.id }));
    const results = await Promise.all(promises);
    const successCount = results.filter(res => res.code === 200).length;

    if (successCount === selectedFiles.value.length) {
      ElMessage.success(`成功删除 ${successCount} 个文件`);
    } else {
      ElMessage.warning(`删除完成，成功 ${successCount} 个，失败 ${selectedFiles.value.length - successCount} 个`);
    }

    await loadFiles();
    selectedFiles.value = [];
  } catch (error) {
    if (error !== 'cancel') {
      console.error("批量删除失败:", error);
      ElMessage.error("批量删除失败，请重试");
    }
  }
};

// 获取文件图标
const getFileIcon = (filename) => {
  if (!filename) return '📄';

  const ext = filename.split('.').pop()?.toLowerCase();

  if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext)) return '🖼️';
  if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'].includes(ext)) return '🎬';
  if (['mp3', 'wav', 'flac', 'aac', 'ogg'].includes(ext)) return '🎵';
  if (['pdf'].includes(ext)) return '📕';
  if (['doc', 'docx'].includes(ext)) return '📘';
  if (['xls', 'xlsx'].includes(ext)) return '📗';
  if (['ppt', 'pptx'].includes(ext)) return '📙';
  if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return '📦';
  if (['txt', 'md', 'json', 'xml', 'csv'].includes(ext)) return '📝';
  if (['js', 'ts', 'html', 'css', 'vue', 'py', 'java', 'cpp'].includes(ext)) return '💻';

  return '📄';
};

// 生命周期
onMounted(() => {
  loadFiles();
});

</script>

<style lang="less" scoped>
.folder-details {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  .header-left {
    display: flex;
    align-items: center;
    gap: 20px;

    .back-btn {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .folder-info {
      display: flex;
      align-items: center;
      gap: 16px;

      .folder-icon {
        width: 50px;
        height: 50px;
        background: linear-gradient(135deg, #ffd54f, #ffb74d);
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 20px;
      }

      .folder-text {
        h2 {
          margin: 0 0 4px 0;
          color: #303133;
          font-size: 20px;
          font-weight: 600;
        }

        p {
          margin: 0;
          color: #606266;
          font-size: 14px;
        }
      }
    }
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.stats-section {
  margin-bottom: 24px;

  .stats-card {
    border-radius: 8px;

    .stats-content {
      display: flex;
      align-items: center;
      gap: 16px;

      .stats-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;

        &.files {
          background: #e3f2fd;
          color: #1976d2;
        }

        &.size {
          background: #f3e5f5;
          color: #7b1fa2;
        }

        &.images {
          background: #e8f5e8;
          color: #388e3c;
        }

        &.videos {
          background: #fff3e0;
          color: #f57c00;
        }
      }

      .stats-info {
        .stats-number {
          font-size: 24px;
          font-weight: 600;
          color: #303133;
          line-height: 1;
        }

        .stats-label {
          font-size: 12px;
          color: #909399;
          margin-top: 4px;
        }
      }
    }
  }
}

.filter-section {
  margin-bottom: 24px;

  .view-controls {
    display: flex;
    justify-content: flex-end;
  }
}

.files-content {
  .empty-state {
    text-align: center;
    padding: 60px 20px;
  }

  .file-cell {
    display: flex;
    align-items: center;
    gap: 8px;

    .file-icon {
      font-size: 16px;
    }

    .file-name {
      font-weight: 500;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .file-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;

    .file-card {
      position: relative;
      border: 1px solid #ebeef5;
      border-radius: 12px;
      cursor: pointer;
      transition: all 0.3s;
      background: white;
      overflow: hidden;

      &:hover {
        border-color: #409eff;
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
        transform: translateY(-2px);

        .file-actions {
          opacity: 1;
        }
      }

      .file-preview {
        height: 120px;
        background: #f5f7fa;
        display: flex;
        align-items: center;
        justify-content: center;

        .file-icon-large {
          font-size: 48px;
        }
      }

      .file-info {
        padding: 16px;

        .file-name {
          font-size: 14px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .file-meta {
          display: flex;
          justify-content: space-between;
          font-size: 12px;
          color: #909399;

          .file-size {
            font-weight: 500;
          }
        }
      }

      .file-actions {
        position: absolute;
        top: 8px;
        right: 8px;
        opacity: 0;
        transition: opacity 0.3s;

        .action-btn {
          width: 28px;
          height: 28px;
          border-radius: 6px;
          background: rgba(255, 255, 255, 0.9);
          border: 1px solid #e4e7ed;

          &:hover {
            background: white;
            border-color: #409eff;
            color: #409eff;
          }
        }
      }
    }
  }
}

.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding: 12px 16px;
  background: #f5f7fa;
  border-radius: 8px;

  .batch-info {
    color: #606266;
    font-size: 14px;
  }

  .batch-buttons {
    display: flex;
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .folder-details {
    padding: 15px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;

    .header-left {
      width: 100%;
      justify-content: center;
    }

    .header-actions {
      width: 100%;
      justify-content: center;
    }
  }

  .stats-section {
    .el-col {
      margin-bottom: 16px;
    }
  }

  .filter-section {
    .el-col {
      margin-bottom: 12px;
    }

    .view-controls {
      justify-content: center;
    }
  }

  .file-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 16px;
  }

  .batch-actions {
    flex-direction: column;
    gap: 12px;
    text-align: center;

    .batch-buttons {
      width: 100%;
      justify-content: center;
    }
  }
}
</style>
